package org.raymond.iworks.study.app;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.raymond.iworks.repository.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.CompletableFuture;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@SpringBootTest
@Slf4j
public class ThreadSelectTest {
    @Autowired
    private TSysUserRepository tSysUserRepository;
    @Autowired
    private TSysRoleRepository tSysRoleRepository;
    @Autowired
    private TSysLogRepository tSysLogRepository;
    @Autowired
    private TSysPermissionRepository tSysPermissionRepository;
    @Autowired
    private TUserRoleRelRepository tUserRoleRelRepository;

    @Test
    public void singleThreadSelectTest(){
        long start = System.currentTimeMillis();
        tSysUserRepository.count();
        tSysRoleRepository.count();
        tSysLogRepository.count();
        tSysPermissionRepository.count();
        tUserRoleRelRepository.count();
        long end = System.currentTimeMillis();
        log.info("single cost:{}", (end-start)); // 90ms
    }

    @Test
    public void multiThreadSelectTest(){
        long start = System.currentTimeMillis();
        CompletableFuture<Long> f1 = CompletableFuture
                .supplyAsync(()->tSysUserRepository.count());
        CompletableFuture<Long> f2 = CompletableFuture
                .supplyAsync(()->tSysRoleRepository.count());
        CompletableFuture<Long> f3 = CompletableFuture
                .supplyAsync(()->tSysLogRepository.count());
        CompletableFuture<Long> f4 = CompletableFuture
                .supplyAsync(()->tSysPermissionRepository.count());
        CompletableFuture<Long> f5 = CompletableFuture
                .supplyAsync(()->tUserRoleRelRepository.count());

        CompletableFuture.allOf(f1,f2,f3,f4,f5).whenComplete((v, e)->{
            if(e!=null){
                e.printStackTrace();
            }else{
                log.info("v:{}", v);
            }
        }).exceptionally(e->{
            e.printStackTrace();
            return null;
        }).join();
        long end = System.currentTimeMillis();
        log.info("multi cost:{}", (end-start)); // 3ms
    }
}
